import router, { asyncRoutes, constantRoutes } from '../../router/index'

const state = () => {
  return {
    allRoutes: constantRoutes
  }
}
const mutations = {
  setRoutes(state, newRoutes) {
    state.allRoutes = newRoutes
  }
}

const actions = {
  filterRoutes(context) {
    // 获取用户可以访问的menus
    const _menus = context.rootState.user.userInfo.roles.menus
    // 和动态路由比较
    const _newRoutes = asyncRoutes.filter(v => {
      const _length = v.children.filter(child => {
        return _menus.includes(child.name)
      })

      if (_length.length > 0) {
        return true
      } else {
        return false
      }
    })
    // const _newRoutes = asyncRoutes.filter(v => {
    //   v.children = v.children.filter(child => {
    //     return _menus.includes(child.name)
    //   })

    //   if (v.children.length > 0) {
    //     return true
    //   } else {
    //     return false
    //   }
    // })
    // 将404页面添加到最后
    _newRoutes.push({ path: '*', redirect: '/404', hidden: true })

    // 动态添加
    router.addRoutes(_newRoutes)
    // 将其合并到vuex默认的数组中
    context.commit('setRoutes', [...constantRoutes, ..._newRoutes])
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
